package com.guizi.halftimesroom.utils;

import android.app.Activity;
import android.os.Handler;


import java.io.IOException;

import okhttp3.Cache;
import okhttp3.Call;
import okhttp3.Callback;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;

/**
 * Created by Alan on 2016/7/19.
 */
public class OkhttpUtil {
    private static Handler handler= new Handler();
    public static void loadData(final Activity activity, String url, final ResponseListener listener) {
        OkHttpClient client = new OkHttpClient.Builder().cache(new Cache(activity.getCacheDir(), 10 <<20)).build();
        Call call = client.newCall(new Request.Builder().url(url).build());
        call.enqueue(new Callback() {
            @Override
            public void onFailure(Call call, IOException e) {

                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listener.onFilure();
                    }
                });
            }

            @Override
            public void onResponse(Call call, Response response) throws IOException {
                final String result = response.body().string();
                activity.runOnUiThread(new Runnable() {
                    @Override
                    public void run() {
                        listener.onSuccess(result);
                    }
                });
            }
        });
    }
}
